package com.cskaoyan.filter;

import com.cskaoyan.servlet.AdminAuthServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        crossOrigin(servletResponse);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //OPTION请求不执行以下代码
        if ("OPTIONS".equals(request.getMethod())){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //1.filter中如果是登录请求，放行
        if ("/admin/auth/login".equals(request.getRequestURI())){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //2.已经登录的状态也可以放行（使用session的值来判断是否登录）
        HttpSession session = request.getSession();
        boolean isLogin = session.getAttribute(AdminAuthServlet.ADMIN_KEY) != null;
        if (isLogin){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

    }

    @Override
    public void destroy() {

    }
    private void crossOrigin(ServletResponse servletResponse) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type,X-CskaoyanMarket-Admin-Token,X-CskaoyanMarket-Token");
        response.setHeader("Access-Control-Allow-Credentials","true");
    }
}
